<?php
/**
 * Nweb Image Manager
 *
 * This script is protected by copyright. It's use, copying, modification
 * and distribution without written consent of the author is prohibited.
 *
 * @category    source
 * @package     pl.nweb.image.adapter
 * @author      Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
 * @copyright   Copyright (c) 2011 Krzysztof Kardasz
 * @license     http://www.gnu.org/licenses/lgpl-3.0.txt  GNU Lesser General Public
 * @version     3.0 $Id: file.php 105 2012-02-24 09:01:04Z krzysztof.kardasz $
 * @link        http://code.google.com/p/nweb-framework/
 * @link        http://framework.nweb.pl
 */

namespace pl\nweb\image\adapter\gd;

/**
 * Utworzenie obrazu z pliku
 *
 * @category    source
 * @package     pl.nweb.image.adapter
 * @author      Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
 * @copyright   Copyright (c) 2011 Krzysztof Kardasz
 * @version     3.0 $Id: file.php 105 2012-02-24 09:01:04Z krzysztof.kardasz $
 */
class File extends \pl\nweb\image\adapter\Gd
{
    /**
     * Konstruktor
     *
     * @param string $file ścieżka do pliku
     * @return void
     * @throws \pl\nweb\image\adapter\gd\Exception
     */
    public function __construct($file)
    {
        if (!is_file($file)) {
            throw new Exception('File "' . $file . '" not found', self::EXCEPTION_FILE_NOT_FOUND);
        }

        $meta = @getimagesize($file);
        if (!$meta) {
            throw new Exception('File "' . $file . '" is not an image', self::EXCEPTION_NOT_AN_IMAGE);
        }

        $obj = new self;

        $obj->_file = $file;
        $obj->_x    = $meta[0];
        $obj->_y    = $meta[1];
        $obj->_type = $meta[2];

        switch ($obj->_type) {
            case IMAGETYPE_JPEG:
                $obj->_im = imagecreatefromjpeg($obj->_file);
            break;
            case IMAGETYPE_PNG:
                $obj->_im = imagecreatefrompng($obj->_file);
                imagealphablending($obj->_im, false);
                imagesavealpha($obj->_im, true);
            break;
            case IMAGETYPE_GIF:
                $obj->_im = imagecreatefromgif($obj->_file);
            break;

            default:
                throw new Exception('Not supported image mime type "' . image_type_to_mime_type($obj->_type) . '"', self::EXCEPTION_UNSUPPORTED);
        }

        return $obj;
    }
}